<!-- 用户管理 -->
<template>
  <div class='userManagement_container main_container'>
    <div style="height: 100%" class="userManagement_box">

      <!-- <div class="left">
        <div class="title_box">
          <span class="title">组织架构</span>
          <el-tooltip content="删除部门" placement="top" effect="dark">
            <i class="deleteGroup" @click="removeGroup"></i>
          </el-tooltip>
          <el-tooltip content="新建部门"  placement="top" effect="dark">
            <i class="addGroup" @click="addGroupFun"></i>
          </el-tooltip>
        </div>
        <div class="genfullAcc">
          <organizationStructure :organData="organData" :organHead="organHead"></organizationStructure>
        </div>
      </div> -->

      <div class="right">
        <div class="search_form_box">
          <el-button @click="addShow" type="primary" size="mini">新增用户</el-button>
          <!-- <el-button @click="changeGroupShow" type="default" size="mini">更换部门</el-button> -->
        </div>

        <div class="table_box">
          <materialTable ref="multipleTable" :tableHead="tableHead" :tableData="tableData" ></materialTable>
        </div>
      </div>
    </div>

    <el-dialog @open="openDialog" :close-on-click-modal="false" :title="dialog.title" custom-class="add_dialog" :visible.sync="dialog.show">
      <div v-if="dialog.title=='新增用户'||dialog.title=='编辑用户'">
        <el-form ref="addForm" :rules="rules" :model="addForm"  label-position="right">
          <form-item 
            label="账户名"  
            model="username" 
            type="input"
            :disabled="dialog.title=='编辑用户'"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="用户姓名"  
            model="realname" 
            type="input"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="性别"  
            model="gender" 
            type="radio"
            :radioList="radioList"
            :addForm="addForm"
          ></form-item>
          
          <form-item 
            label="手机号"  
            model="mobile" 
            type="input"
            maxlength="11"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="邮箱"  
            model="email" 
            type="input"
            :disabled="dialog.title=='查看用户'"
            :addForm="addForm"
          ></form-item>
        </el-form>
      </div>

      <!-- 修改部门 -->
      <div v-if="dialog.title=='编辑部门'||dialog.title=='更换人员部门'">
        <el-tree
          :data="organData"
          highlight-current
          node-key="index"
          ref="tree"
          show-checkbox
          default-expand-all
          :default-expanded-keys="treeChecked"
          :default-checked-keys="treeChecked"
          @check-change="handleNodeClick"
        ></el-tree>
      </div>


      <div v-if="dialog.title=='设置角色'">
        <el-form :model="setRole" label-position="left" ref="roleForm">
          <el-form-item label="设置角色 : ">
            <el-checkbox-group v-model="setRole.roleIds" autocomplete="off" style="width:100%">
              <el-checkbox
                v-for="item in roleListData"
                :label="item.roleId"
                :key="item.roleId"
              >{{item.roleName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button type="default" size="mini" @click="dialog.show = false">取 消</el-button>

        <el-button type="primary" :loading="btnLoading" size="mini" @click="setUserSub" v-if="dialog.title=='更换人员部门'">确 定</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" @click="setRoleSub" v-if="dialog.title=='设置角色'">确 定</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" @click="addSubmit" v-if="dialog.title=='新增用户'">确 定</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" @click="editSubmit" v-if="dialog.title=='编辑用户'">确 定</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" @click="editOrganSubmit" v-if="dialog.title=='编辑部门'">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import materialTable from "@/components/assembly/materialTable";
import pagination from "@/components/assembly/pagination";
import organizationStructure from "@/components/assembly/organizationStructure";
import { createNamespacedHelpers } from "vuex";
let { mapActions } = createNamespacedHelpers("userManagement");
let myVue = {};
let obj = {};

export default {
  name: 'userManagement',
  data() {
    return {
      siteId: '10',
      btnLoading: false,
      shakeId: 0,
      siteId: "",
      isAdmin: 0,
      organId: "",
      organItemData: {},
      listOrganId: "",
      listUserId: "",
      listUserType: "",
      editOrganId: "",
      treeChecked: [],
      radioList: [
        { value: 1, label: '男' },
        { value: 0, label: '女' },
      ],
      dialog: {
        title: "",
        show: false
      },
      active_num: 0,
      tableHead: {
        selection: {
          fun: this.handleSelectionChangeDelete
        },
        keyId: 'accountId',
        setFunction: [
          {
            fun: this.editShow,
            name: "编辑",
          },
          {
            fun: this.lockedFun,
            name: "禁用",
            hideKey: "locked",
            hideState: "0",
          },
          {
            fun: this.lockedFun,
            name: "启用",
            hideKey: "locked",
            hideState: "1",
          },
          {
            fun: this.resetPassword,
            name: "重置密码",
            hideKey: "locked",
            hideState: "0"
          },
          {
            fun: this.deleteShow,
            name: "删除",
          },
          {
            fun: this.setRoleShow,
            name: "设置角色",
            hideKey: "locked",
            hideState: "0",
          },
        ],
        noDataText: "暂无成员",
        data: [
          {
            name: "登录名",
            key: "username",
          },
          {
            name: "姓名",
            key: "realname",
          },
          {
            name: "部门名称",
            key: "orgStr",
          },
          {
            name: "角色名称",
            key: "roleStr",
          },
          {
            name: "手机号",
            key: "mobile",
          },
          {
            name: "邮箱",
            key: "email",
          },
          {
            name: "账号状态",
            key: "locked",
            filter: {
              1: "禁用",
              0: "启用"
            }
          }
        ]
      },
      tableData: [],

      organHead: {
        type: "edit",
        keyId: "organId",
        save: this.addGroupSubmit,
        eliminate: this.eliminateFun,
        // eliminate: '',
        // edit: "",
        editFun: this.editFun,
        remove: this.removeGroup,
        clickFun: this.clickOrgan
      },
      organData: [],
      organData2: [],
      editForm: {
        organName: "",
        organId: [],
        parent: []
      },
      selectArr: [],
      userIdArr: [],
      newGroupitem: {
        label: "新建部门",
        organId: "",
        parent: ""
      },
      ungrouped: {
        label: "其他成员"
      },
      adminCheck: false,
      ungroupActive: true,

      addForm: {
        username: "",
        realname: "",
        gender: '',
        mobile: "",
        email: ""
      },
      roleListData: [],
      setRole: {
        roleIds: [],
        userId: ""
      },
      rules: {
        username: [
          { required: true, message: '请输入账户名称', trigger: 'change' }
        ],
        realname: [
          { required: true, message: '请输入真实姓名', trigger: 'change' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
      },

    }
  },

  beforeCreate() {
    myVue = this;
  },
  created() {
    this.siteId = JSON.parse(localStorage.getItem("jwtAuth")).extMap.siteId;
    // this.initGroupTree();
    this.initData();
  },

  mounted() {
    
  },
  

  methods: {
    ...mapActions(["formGet", "post"]),

    handleSelectionChange(item) {
      this.selectArr = item;
    },

    setRoleShow(rowData) {
      this.setRole = {
        roleIds: [],
        userId: rowData.row.userId
      };
      this.post({
        API: "roleList",
        data: {
          siteId: rowData.row.siteId
        }
      }) .then(res => {
        this.roleListData = res;
      }) .catch(err => {
        this.$message.error(err);
      });

      this.post({
        API: "setRoleList",
        data: {
          userId: rowData.row.userId
        }
      }).then(res => {
        let arr = [];
        for (let i in res) {
          arr.push(res[i].roleId);
        }
        this.setRole.roleIds = arr;
        this.dialog = {
          title: "设置角色",
          show: true
        };
      }).catch(err => {
        this.$message.error(err);
      });
    },

    setRoleSub() {
      // if (this.setRole.roleIds == "") {
      //   this.$message.error("请绑定角色");
      //   return false;
      // }
      this.btnLoading = true
      if(this.setRole.roleIds instanceof Array) {
        this.setRole.roleIds = this.setRole.roleIds.join(",");
      }

      this.post({
        API: "setRole",
        data: this.setRole
      }).then(res => {
        this.$message.success("设置成功");
        this.dialog.show = false;
        this.initData();
      }).catch(err => {
        this.$message.error(err);
      });
    },

    // 加载 树
    initGroupTree() {
      this.post({
        API: "queryGroupTree",
        data: {
          siteId: this.siteId
        }
      })
        .then(res => {
          this.organData = JSON.parse(JSON.stringify(res));
          this.organData2 = JSON.parse(JSON.stringify(res));
          this.initData();
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 加载 列表
    initData(organId) {
      let data = {};
      if (organId || this.organId) {
        data.organId = organId || this.organId;
      } else {
        data.siteId = this.siteId;
      }
      this.post({
        API: "selectTmProjectGroupPageList",
        data: data
      }).then(res => {
        this.tableData = res;
        this.$refs.multipleTable.$children[0].clearSelection();
      }) 
      .catch(err => {
        this.$message.error(err);
      });
    },
    editShow(row) {
      
      this.formGet({
        API: 'selectById',
        data: {
          id: row.row.userId
        }
      }).then(res => {
        this.dialog = {
          title: "编辑用户",
          show: true
        };
        this.addForm = res;

        this.listOrganId = res.organId;
        this.listUserType = res.userType;
        this.listUserId = res.userId;
      })
      
    },
    editSubmit() {
      this.btnLoading = true

      this.addForm.siteId = this.siteId;
      this.addForm.organId = this.listOrganId;
      this.addForm.userId = this.listUserId;
      this.addForm.userType = this.listUserType;

      this.post({
        API: "edit",
        data: this.addForm
      })
        .then(res => {
          this.$message.success("编辑成功");
          this.dialog.show = false;
          this.initData();
        })
        .catch(err => {
          this.$message.error(err);
          this.btnLoading = false
        });
    },
    // 添加新账户
    addShow() {
      if (this.organId == "") {
        this.$message.warning("请选择左侧组织架构");
        return false;
      }
      
      this.addForm = {
        username: "",
        realname: "",
        gender: "",
        mobile: "",
        email: ""
      }

      this.dialog = {
        title: "新增用户",
        show: true
      }
    },
    addSubmit() {
      this.addForm.siteId = this.siteId;
      this.addForm.organId = this.organId;
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.post({
            API: "add",
            data: this.addForm
          })
            .then(res => {
              this.$message.success("新增成功");
              this.dialog.show = false;
              this.initData();
            })
            .catch(err => {
              this.$message.error(err);
              this.btnLoading = false
            });
          } else {
          return false;
        }
      });
    },
    deleteShow(row) {
      this.$confirm("是否确认删除", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning"
      }).then(() => {
        this.deleteSubmit(row);
      });
    },
    deleteSubmit(row) {
      this.btnLoading = true
      this.formGet({
        API: 'deleteById',
        data: {
          id: row.row.userId
        }
      }).then(res => {
        this.initData();
        this.$message.success('删除成功');
      }).catch(err => {
        this.$message.error(err);
        this.btnLoading = false
      })
    },

    // 更换人员部门
    changeGroupShow() {
      this.dialog = {
        show: true,
        title: "更换人员部门"
      };
      this.$nextTick(() => {
        if(this.organItemData.index) {
          this.$refs.tree.setCheckedKeys([this.organItemData.index]);
        }else {
          this.$refs.tree.setCheckedKeys([]);
        }
      })

      if (this.userIdArr == "") {
        this.$message.warning("请勾选要更改的人员");
        return false;
      }
      this.editForm.parent = this.organId;
      
    },
    // 更换人员部门 提交
    setUserSub() {
      this.btnLoading = true
      let userId = this.userIdArr.join(",");
      this.post({
        API: "updateUserGroup",
        data: {
          organId: this.editForm.parent,
          userId: userId
        }
      })
        .then(res => {
          this.$message.success("更改成功");
          this.dialog.show = false;

          this.initGroupTree();
        })
        .catch(err => {
          this.$message.error(err);
          this.btnLoading = false
        });
    },

    handleSelectionChangeDelete(item) {
      for (let i = 0; i < item.length; i++) {
        if (item[i].isCreate == 1) {
          // 1 为管理员，不可移除
          this.adminCheck = true;
          break;
        } else {
          this.adminCheck = false;
        }
      }
      this.userIdArr = [];
      item.forEach(item => {
        this.userIdArr.push(item.userId);
      });
    },

    // 编辑 项目组织架构
    editFun(data) {
      console.log(data);
      this.dialog = {
        show: true,
        title: "编辑部门"
      };
      this.editForm.parent = data.parent;

      this.editForm.organName = data.label;
      this.editForm.organId = data.organId;
      this.treeChecked = [data.index];
    },

    // 编辑部门 提交
    editOrganSubmit() {
      this.btnLoading = true
      this.post({
        API: "update",
        data: {
          organId: this.editForm.organId,
          organName: this.editForm.organName,
          parent: this.editForm.parent,
          siteId: this.siteId
        }
      })
        .then(res => {
          this.$message.success("编辑成功");
          this.dialog.show = false;

          this.initGroupTree();
        })
        .catch(err => {
          this.$message.error(err);
          this.btnLoading = false
        });
    },

    removeGroup(data) {
      if(!this.organId) {
        this.$message.warning('请选择要删除的部门')
        return false;
      }
      this.$confirm("是否确认删除该部门", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning"
      }).then(() => {
        this.deleteGroupSubmit();
      });
    },
    // 删除部门 提交
    deleteGroupSubmit() {
      this.btnLoading = true
      if (this.organItemData.children) {
        this.$message.warning("该部门下有子部门，无法删除!");
        return false;
      }

      this.formGet({
        API: "delete",
        data: {
          id: this.organId
        }
      })
        .then(res => {
          this.$message.success("删除成功");
          (this.organId = ""), this.initGroupTree();
        })
        .catch(err => {
          this.$message.error(err);
          this.btnLoading = false
        });
    },
    // 新建部门
    addGroupFun() {
      let organId = this.organId;
      console.log(organId)
      if(!organId) {
        // this.$message.warning('请选择父级架构')
        // return false;
      }
      if (!this.organData[0].children) {
        this.organData[0].children = [];
      }
      let organData = this.organData[0].children;

      if (organData[0]) {
        if (organData[0].newNode) {
          return false;
        }
      }

      let obj = {
        label: "新建部门",
        organId: "",
        newNode: true
      };
      // let obj = myVue.newGroupitem;

      if (!organId) {
        this.organData[0].children.splice(0, 0, obj);
        this.organData[0].children.switchs = 0;
        return false;

        // this.$message.error('请选择要添加部门的父级')
        // return false
      }

      var forOrgan = function(data) {
        data.forEach(item => {
          if (item.organId === organId) {
            // 找到对应 ID 的节点 ，插入新部门

            obj = {
              label: "新建部门",
              organId: "",
              newNode: true,
              parent: organId
            };
            if (item.children) {
              // if (!item.children[0] && !item.children[0].newNode) {
              item.children.unshift(obj);
              // }
            } else {
              myVue.$set(item, "children", []);
              item.children.unshift(obj);
            }
          } else {
            if (item.children) {
              forOrgan(item.children);
            } else {
            }
          }
        });
      };
      forOrgan(this.organData);
    },

    deleteGroupFun() {
      
    },

    addGroupSubmit(data) {
      this.btnLoading = true
      // let obj={};
      obj.parent = this.organId || 0;
      obj.siteId = this.siteId;
      obj.organName = data.label;
      // data.parent = 0;
      if (!this.organId) {
        this.newGroupitem.parent = 0;
      }
      this.post({
        API: "addGroup",
        data: obj
      })
        .then(res => {
          this.$message.success("新建部门成功");
          this.initGroupTree();
          obj = {};
          return true;
        })
        .catch(err => {
          this.$message.error(err);
          this.btnLoading = false
          return false;
        });
    },

    eliminateFun() {},
    // 点击 部门树节点
    clickOrgan(data) {
      this.ungroupActive = false;
      this.active_num = data.$treeNodeId;
      console.log(data);
      // if (data.organId) {
      this.organId = data.organId;
      this.organItemData = data;
      // }
      // if (this.organId) {
      this.initData();
      // }
      if (this.organId) {
        this.treeChecked = [data.index];
      } else {
        this.treeChecked = [];
      }
    },
    lockedFun(e) {
      if (e.row.locked == 0) {
        var bool = 1;
      } else {
        var bool = 0;
      }
      this.post({
        API: "locked",
        data: {
          locked: bool,
          userId: e.row.userId
        }
      })
        .then(res => {
          if (e.row.locked == 0) {
            this.$message.success("禁用成功");
          } else {
            this.$message.success("启用成功");
          }
          this.initData();
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    resetPassword(e) {
      this.$confirm("确认重置密码为“A123456”", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning"
      }).then(() => {
        this.formGet({
          API: "resetPassword",
          data: {
            userId: e.row.userId
          }
        })
          .then(res => {
            this.$message.success("密码重置成功");
          })
          .catch(err => {
            this.$message.error(err);
          });
      });
    },
    // 编辑部门点击
    handleNodeClick(data, checked, indeterminate) {
      // console.log(data);
      // console.log(checked);
      // console.log(indeterminate);
      if (checked) {
        this.editForm.parent = data.organId;
        this.$refs.tree.setCheckedKeys([data.index]);
      }
    },

    
    openDialog() {
      if(this.$refs.addForm) {
        this.$refs.addForm.resetFields();
      }
      this.btnLoading = false
    },
  },

  components: {
    materialTable,
    pagination,
    organizationStructure,
  }
}
</script>

<style scoped lang="less">
.userManagement_container {
  .userManagement_box {
    display: flex;
    flex-wrap: nowrap;
    width: 100%;
  }
  .left {
    width: 300px;
    padding: 20px 10px;
    box-sizing: border-box;
    .title_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
      .title {
        color: #303133;
        font-size: 16px;
      }
      i {
        width: 20px;
        height: 20px;
        display: inline-block;
        cursor: pointer;
      }
      .addGroup {
        background: url('../../../../assets/img/add.png') 0 0 no-repeat;
        background-size: 100%;
      }
      .deleteGroup {
        background: url('../../../../assets/img/delete.png') 0 0 no-repeat;
        background-size: 100%;
        margin-left: auto;
        margin-right: 10px;
      }
    }
  }
  .right {
    flex: 1;
  }
  .table_box {
    height: calc(100% - 55px);
  }
}
</style>